import java.sql.*;
import java.util.*;

/**
 * 数据库访问对象类，负责处理所有与数据库相关的操作
 */
public class TaskDAO {
    // 数据库连接信息
    private static final String URL = "jdbc:mysql://localhost:3306/timerdb?useSSL=false&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";

    /**
     * 构造函数，加载MySQL驱动
     */
    public TaskDAO() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有任务列表
     * @return 任务列表，按ID降序排列
     */
    public List<Task> getAllTasks() {
        List<Task> list = new ArrayList<>();
        String sql = "SELECT * FROM tasks ORDER BY id DESC";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                Task t = new Task(
                    rs.getInt("id"),
                    rs.getString("name"),
                    rs.getTimestamp("start_time"),
                    rs.getTimestamp("end_time"),
                    rs.getInt("duration_seconds")
                );
                list.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 添加新任务
     * @param name 任务名称
     */
    public void addTask(String name) {
        String sql = "INSERT INTO tasks (name) VALUES (?)";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, name);
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除指定任务
     * @param id 要删除的任务ID
     */
    public void deleteTask(int id) {
        String sql = "DELETE FROM tasks WHERE id=?";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, id);
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 完成任务，更新任务的开始时间、结束时间和持续时间
     * @param id 任务ID
     * @param start 开始时间
     * @param end 结束时间
     * @param durationSeconds 持续时间（秒）
     */
    public void finishTask(int id, java.util.Date start, java.util.Date end, int durationSeconds) {
        String sql = "UPDATE tasks SET start_time=?, end_time=?, duration_seconds=? WHERE id=?";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setTimestamp(1, new java.sql.Timestamp(start.getTime()));
            ps.setTimestamp(2, new java.sql.Timestamp(end.getTime()));
            ps.setInt(3, durationSeconds);
            ps.setInt(4, id);
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}